<template>
	<view class="flex w_100 h_100 kn_editor position-relative border-box rounded-radius-l items-center">
		<editor id="editor" class="editor_wrapper" :placeholder="placeholder" :showImgSize="false"
			:showImgToolbar="false" :showImgResize="false" @statuschange="onStatusChange" :read-only="readOnly"
			@ready="onEditorReady" @focus="bindfocus" @blur="bindblur" @input="bindinput" :style="{
					maxHeight:maxHeight,
					height:height
				}"></editor>
	</view>
</template>

<script>
	/**
	 * @author		前端小能手
	 * 富文本编辑主体
	 */

	export default {
		props: {
			readOnly: {
				type: Boolean,
				default: false,
			},
			value: {
				type: String,
				default: '',
			},
			iosScroll: {
				type: Boolean,
				default: false,
			},
			pageScrollTop: {
				type: Number,
				default: 0,
			},
			showInsertImg: {
				type: Boolean,
				default: true
			},
			placeholder: {
				type: String,
				default: '',
			},
			maxHeight: {
				type: String,
				default: '',
			},
			height: {
				type: String,
				default: '',
			}
		},
		data() {
			return {
				editorCtx: {}, // 富文本对象
				showM: false, // 显示清空警告
				formats: {}, // 当前文本样式
				content: "",
				triggeredPositions: new Set()
			}
		},
		methods: {
			//编辑器初始化完成时触发
			onEditorReady() {
				this.$emit('onEditorReady') // 返回一个 SelectorQuery 对象实例。在自定义组件或包含自定义组件的页面中，应使用this.createSelectorQuery()来代替。
				uni
					.createSelectorQuery()
					.in(this)
					.select('#editor')
					.context((res) => {
						this.editorCtx = res.context
						let rtTxt = this.value
						this.setContents(rtTxt) //设置富文本内容
					})
					.exec()
			},
			// 键盘变化
			keyChange(height) {
				this.$emit('keyChange', height)
			},
			//设置富文本内容
			setContents(rechtext) {
				this.editorCtx.setContents({
					html: rechtext,
					success: (res) => {},
				})
			},
			//编辑器聚焦时触发
			bindfocus(res) {
				this.$emit('bindfocus', {
					detail: {
						value: res,
					},
				})
			},
			// 插入内容
			insertContent(html) {
				this.editorCtx.insertText({
					text: html,
					complete: () => {
						
					}
				})
			},
			//编辑器失去焦点时触发
			bindblur(res) {
				this.$emit('bindblur', {
					detail: {
						value: res,
					},
				})
			},
			topLTap() {
				this.editorCtx.format('fontFamily', '')
			},
			clear() {
				this.showM = true
			},
			//清空编辑器内容
			clearContent() {
				this.editorCtx.clear({
					success: (res) => {
						this.showM = false
						this.$emit('clearSuccess')
					},
				})
			},
			// 通过 Context 方法改变编辑器内样式时触发，返回选区已设置的样式
			onStatusChange(res) {
				console.log(res.detail)
				// const formats = res.detail
				// this.formats = formats
			},
			//编辑器输入中时触发
			bindinput(res) {
				const val = res.detail.html
				this.$emit('input', val)

				// 解析内容并检测 @ 符号
				this.detectAtSymbols(val);
			},
			detectAtSymbols(content) {
				// 正则表达式匹配 @ 符号和其位置
				const atSymbolRegex = /@/g;
				let match;
				const positions = [];

				while ((match = atSymbolRegex.exec(content)) !== null) {
					positions.push(match.index);
				}

				// 遍历所有 @ 符号的位置
				positions.forEach(position => {
					// 如果该位置之前没有触发过事件，则触发事件
					if (!this.triggeredPositions.has(position)) {
						this.triggeredPositions.add(position);
						this.triggerEvent(content);
					}
				});

				// 清理删除的 @ 符号的位置
				this.cleanUpTriggeredPositions(positions);
			},
			triggerEvent(content) {
				this.$emit('inputA', content)
			},
			cleanUpTriggeredPositions(currentPositions) {
				// 从已触发位置中删除那些不再存在的 @ 符号位置
				this.triggeredPositions.forEach(position => {
					if (!currentPositions.includes(position)) {
						this.triggeredPositions.delete(position);
					}
				});
			},
			//恢复
			redo() {
				this.editorCtx.redo()
				this.$emit('restore')
			},
			save() {
				this.editorCtx.getContents({
					success: (res) => {
						this.$emit('getEditorContent', {
							detail: {
								value: res,
							},
						})
					},
				})
			},
			// 选择图片
			insertImageEvent() {
				let that = this
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.$emit('uploadImgBefore', res.tempFiles[0])
					},
				})
			},
			// 插入图片
			insertImage(img) {
				this.editorCtx.insertImage({
					src: img,
					width: '20px',
					height: '20px',
					extClass: 'image'
				});
			}
		},
	}
</script>

<!-- #ifdef MP-WEIXIN -->
<style>
	.editor_wrapper {
		min-height: 30rpx !important;
	}

	#editor .image {
		vertical-align: middle;
	}
</style>
<!-- #endif -->


<style scoped>
	@import url("./common.css");

	/deep/ .ql-container {
		min-height: 30rpx !important;
	}

	.editor_wrapper {
		height: auto;
	}

	.handle_bar {
		height: 60rpx;
		width: 60rpx;
	}

	.handle_icon {
		height: 30rpx;
	}

	.pb_80 {
		padding-bottom: 80rpx;
	}

	/deep/ .ql-image-toolbar {
		display: none !important;
	}

	/deep/ .ql-image-size {
		display: none !important;
	}

	/deep/ .ql-image-handle {
		display: none !important;
	}

	/deep/ .ql-container .ql-image-overlay {
		border: none !important;
	}

	/deep/ .ql-editor p {
		width: 100%;
	}

	/deep/ .ql-editor p img {
		width: 44rpx;
		height: 44rpx;
		vertical-align: middle;
	}
</style>